﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace PhoneBook.Controllers
{
    public class AccountController : Controller
    {
        // GET: /<controller>/
        public async Task<string> Login()
        {
            string name = "admin";
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, name));
            var indentity = new ClaimsIdentity(claims, "denglu");
            var principal = new ClaimsPrincipal(indentity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
            return "成功";
        }

        public async Task<string> Login2()
        {         
            return "请求登录";
        }

        [HttpPost]
        public async Task<IActionResult> Login(string name,string pwd)
        {
            if (ModelState.IsValid)
            {
                //登陆授权
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, name));
                var indentity = new ClaimsIdentity(claims, "denglu");
                var principal = new ClaimsPrincipal(indentity);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,principal);
                //验证是否授权成功
                if (principal.Identity.IsAuthenticated)
                {
                    return RedirectToPage("Index");
                }
            }
            return View();
        }

        public string TestLogin()
        {
            return HttpContext.User.Identity.IsAuthenticated.ToString();
        }

        [Authorize]
        public string TestLogin2()
        {
            return "成功 authorize";
        }

        public async Task<IActionResult> LoginOut()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {

                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            }
            return RedirectToAction("Login");

        }
    }
}
